package model

import (
	"github.com/jinzhu/gorm"
	"github.com/satori/go.uuid"
	"time"
)

type Bill struct {
	BaseModel
	Amount     float64 `json:"amount"`
	Use        string  `json:"use"`
	CategoryId string  `json:"categoryId"`
	Imgs       string  `json:"imgs"`
	Location   string  `json:"location"`
}

func (b Bill) TableName() string {
	return "tb_bill"
}

func (b *Bill) Create() error {
	return DB.Self.Create(&b).Error
}

func (b *Bill) BeforeCreate(scope *gorm.Scope) error {
	u4, _ := uuid.NewV4()
	scope.SetColumn("Id", u4.String())
	scope.SetColumn("created_time", time.Now())
	scope.SetColumn("created_by", "system")
	scope.SetColumn("updated_time", time.Now())
	scope.SetColumn("updated_by", "system")
	return nil
}

func (b *Bill) BeforeUpdate() error {
	b.UpdatedTime = time.Now()
	return nil
}

func DeleteBill(id string) error {
	bill := Bill{}
	bill.Id = id
	return DB.Self.Delete(&bill).Error
}

func (b *Bill) Update() error {
	return DB.Self.Save(&b).Error
}

func ListBill(offset, limit int) ([]*Bill, uint64, error) {
	if limit == 0 {
		limit = 10
	}
	bills := make([]*Bill, 0)

	var count uint64
	if err := DB.Self.Model(&Bill{}).Count(&count).Error; err != nil {
		return bills, count, err
	}
	if err := DB.Self.Offset(offset).Limit(limit).Order("created_time asc").Find(&bills).Error; err != nil {
		return bills, count, err
	}

	return bills, count, nil
}

func GetBillById(id string) (*Bill, error) {
	var bill Bill
	d := DB.Self.First(&bill)
	return &bill, d.Error
}
